package cn.bone.base.jms1;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by MD-01 on 2016/9/9.
 */
public class Sender {

    public static void main(String[] args) {

        // 连接工厂,JMS用他创建连接
        ConnectionFactory connectionFactory;

        // JMS客户端到JMS Provider的连接
        Connection connection = null;

        // 一个发送或接收消息的线程
        Session session;

        // 消息的目的地,消息发送给谁
        Destination destination;

        // 消息发送者
        MessageProducer producer;

        // 构造ConnectionFactory对象
        connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                ActiveMQConnection.DEFAULT_BROKER_URL);

        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE);

            destination = session.createQueue("FirstQueue");

            // 得到消息生成者【发送者】
            producer = session.createProducer(destination);
            // 设置不持久化，此处学习，实际根据项目决定
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(session, producer);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != connection) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                } finally {
                    connection = null;
                }
            }
        }
    }

    public static void sendMessage(Session session, MessageProducer producer)
            throws Exception {
        for (int i = 1; i <= 5; i++) {
            TextMessage message = session.createTextMessage("ActiveMq 发送的消息:"
                    + i);

            System.out.println("发送消息：" + "ActiveMq 发送的消息" + i);
            producer.send(message);
        }
    }
}
